import './App.css'
import { tree } from './mock';
import React, { useState, useMemo, useRef } from 'react';
import { useGetState } from 'ahooks';
import { Tree, Input, Space } from 'antd';
import {
  DownOutlined,
  UpOutlined,
} from '@ant-design/icons';

const { Search } = Input;

function App() {
  const { data } = tree ?? {};

  const treeRef = useRef(null);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [searchList, setSearchList] = useState([]);
  const [count, setCount, getCount] = useGetState(0);

  const up = () => {
    let ind = getCount() - 1;
    if (ind >= 0) {
      setCount((state) => --state);
      // 注意：如果要用这个要关掉虚拟滚动，不然找不到对应的id 
      document.getElementById(searchList[ind]).scrollIntoView({behavior: "auto", block: "center", inline: "nearest"}); 
      // treeRef.current.scrollTo({ key: searchList[ind], align: 'auto' });
    }
  };

  const down = () => {
    let ind = getCount() + 1;
    if (ind < searchList?.length) {
      setCount((state) => ++state);
      document.getElementById(searchList[ind]).scrollIntoView({behavior: "auto", block: "center", inline: "nearest"});
      // treeRef.current.scrollTo({ key: searchList[ind], align: 'auto' });
    }
  };

  const treeData = useMemo(() => {
    let ind = 0;
    const loop = (origin) =>
      origin.map((item) => {
        const strTitle = item.title;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span id={searchList[ind]}>
              {beforeStr}
              <span
                style={{
                  background:
                    searchList?.[count] === searchList[ind]
                      ? 'orange'
                      : 'yellow',
                }}
              >
                {searchValue}
              </span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (index > -1) ind = ++ind;
        if (item.children) {
          return {
            title,
            key: item.key,
            children: loop(item.children),
          };
        }
        return {
          title,
          key: item.key,
        };
      });
    return loop(data);
  }, [searchValue, down, up])

  
  const onExpand = (keys) => {
    setExpandedKeys(keys);
    setAutoExpandParent(true);
  }

  const getParentKey = (key, list) => {
    let parentKey;
    for (let i = 0; i < list.length; i++) {
      const node = list[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  // 扁平化树
  const flatTree = (orgin) => {
    const newArr = [];
    const loop = (data) => {
      data?.forEach(item => {
        if (item?.children?.length) {
          loop(item?.children);
        }
        newArr.push(item);
      })
    }
    loop(orgin);
    return newArr;
  }

  // 搜索过滤节点
  const onChange = (e) => {
    const { value } = e.target ?? {};
    const list = [];
    const newKeys = flatTree(data)?.map(item => {
      if (!!value && item?.title.includes(value)) {
        list.push(item?.key);
        return getParentKey(item?.key, data);
      }
      return null;
    })
    setSearchList(list);
    setExpandedKeys(new Set(newKeys));
    setSearchValue(value);
    setAutoExpandParent(true);
  }

  return (
    <div className="App">
      <div style={{ position: 'relative' }}>
        <Search
          style={{
            marginBottom: 8,
          }}
          onChange={onChange}
        />
        {(searchValue && searchList?.length) ? (
          <Space
            size="small"
            style={{ position: 'absolute', top: '6px', right: '35px', zIndex: '999' }}
          >
            {`${count + 1}/${searchList?.length}`}
            <UpOutlined style={{ color: '#4E8CE5' }} onClick={up} />
            <DownOutlined style={{ color: '#4E8CE5' }} onClick={down} />{' '}
          </Space>
        ) : null}
      </div>
      <Tree
        ref={treeRef}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        treeData={treeData}
        height={600}
        virtual={false}
        style={{ width: 200 }}
      />
    </div>
  )
}

export default App
